package rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class Consumer1 {

	private final static String QUEUE_NAME="hello2";
	
	public static void main(String[] args) {
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			Connection connect = factory.newConnection();
			Channel channel = connect.createChannel();
			//第一个布尔值 durable：true 如果我们声明一个持久队列（队列将在服务器重新启动时幸存）
			//第二个布尔值exclusive ：是否为当前连接的专用队列，在连接断开后，会自动删除该队列。
			//第三个布尔值autodelete：true当没有任何消费者使用时，自动删除该队列。
			channel.queueDeclare(QUEUE_NAME, true,false,false,null);
			//每次从队列中获取的数量。0为不限制。true是整个channel,而不是每个消费者
			channel.basicQos(2);
			System.out.println("C [*] Waiting for messages. To exit press CTRL+C");
			Consumer consumer = new DefaultConsumer(channel) {

				@Override
				public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
						byte[] body) throws IOException {
//					super.handleDelivery(consumerTag, envelope, properties, body);
					String str = new String(body,"utf-8");
					System.out.println("消费者1收到消息收到消息===============》"+str);
					try {
//						doWork(str);
					} finally{
						//消息处理完成确认.envelope.getDeliveryTag()：消息的index.true:批量处理。false:单个处理
						channel.basicAck(envelope.getDeliveryTag(), true);
					}
				}
			};
			//消息消费完成确认
			//autoAck：是否自动ack，如果不自动ack，需要使用channel.ack、channel.nack、channel.basicReject 进行消息应答
			channel.basicConsume(QUEUE_NAME,false,consumer);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
	}
	
	 private static void doWork(String task) {
	        try {
	            Thread.sleep(1000); // 暂停1秒钟
	        } catch (InterruptedException _ignored) {
	            Thread.currentThread().interrupt();
	        }
	    }
}
